package com.mvp.lt.airlineview.map;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.services.core.ServiceSettings;
import com.mvp.lt.airlineview.App;
import com.mvp.lt.airlineview.R;
import com.mvp.lt.airlineview.base.BaseActivity;
import com.mvp.lt.airlineview.location.DipType;
import com.mvp.lt.airlineview.utils.LogUtil;
import com.mvp.lt.airlineview.utils.RouteUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * $activityName
 * 多边形 正射
 *
 * @author LiuTao
 * @date 2019/3/27/027
 */


public class PolygonLineActivity extends BaseActivity {
    @BindView(R.id.map_view)
    MapView mMapView;
    @BindView(R.id.seekbar_head)
    SeekBar seekbarHead;
    @BindView(R.id.seekbar_edg)
    SeekBar seekbarDdg;

    @BindView(R.id.rotationValue)
    TextView rotationValue;
    @BindView(R.id.edgValue)
    TextView edgValue;


    @BindView(R.id.diskOverlapRatio)
    SeekBar diskOverlapRatio;
    @BindView(R.id.diskOverlapRatioValue)
    TextView diskOverlapRatioValue;

    @BindView(R.id.flyHeightValueSeekBar)
    SeekBar flyHeightValueSeekBar;

    @BindView(R.id.flyHeightValue)
    TextView flyHeightValue;

    @BindView(R.id.tiltAngleValueSeekBar)
    SeekBar tiltAngleValueSeekBar;

    @BindView(R.id.tiltAngleValue)
    TextView tiltAngleValue;

    @BindView(R.id.radio_group)
    RadioGroup radioGroup;

    @BindView(R.id.radio_button1)
    RadioButton radioButton1;

    @BindView(R.id.radio_button2)
    RadioButton radioButton2;

    @BindView(R.id.radio_button3)
    RadioButton radioButton3;

    @BindView(R.id.radio_button4)
    RadioButton radioButton4;

    @BindView(R.id.radio_button5)
    RadioButton radioButton5;

    private boolean isFirstLoc = true;


    private Marker mTagmarker;
    LatLng leftLatLng = new LatLng(27.259653, 111.54144);
    LatLng rightLatLng = new LatLng(27.259653, 111.64244);
    //28.166298552510284================113.02671552060417
    LatLng mLatLng = new LatLng(28.166298552510284, 113.02671552060417);


    public static void show(Context context) {
        Intent intent = new Intent(context, PolygonLineActivity.class);

        context.startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_polygon);
        ButterKnife.bind(this);
        initView();

        // initLocation();
        MapCreateManager.getMapManager().setMapView(this,mMapView).buildMap(savedInstanceState);
//        //加载自定义wms
//        HeritageScopeTileProvider tileProvider = new HeritageScopeTileProvider();
//        MapCreateManager.getMapManager().getaMap().addTileOverlay(new TileOverlayOptions()
//                .tileProvider(tileProvider)
//                .zIndex(-0.1f)
//                .diskCacheDir("/storage/amap/cache")
//                .diskCacheEnabled(true)
//                .diskCacheSize(100));
        //左边的点 黄色
        MapCreateManager.getMapManager().addMarker(leftLatLng);
        //右边边的点 绿色
        MapCreateManager.getMapManager().addMarker1(rightLatLng);
        //划线
        MapCreateManager.getMapManager().drawLine(leftLatLng, rightLatLng);
        //求左边点的外扩点 向左外扩
        LatLng latLng0 = MapCalculationLogLatDistance.getDistanceExpansionPoint(rightLatLng.longitude, rightLatLng.latitude, leftLatLng.longitude, leftLatLng.latitude, 100);
        MapCreateManager.getMapManager().addMarker3(latLng0);
        MapCreateManager.getMapManager().drawLine(leftLatLng, latLng0);
        //求右边点的外扩点 向右外扩
        LatLng latLng1 = MapCalculationLogLatDistance.getDistanceExpansionPoint(leftLatLng.longitude, leftLatLng.latitude, rightLatLng.longitude, rightLatLng.latitude, 100);

        MapCreateManager.getMapManager().addMarker2(latLng1);
        MapCreateManager.getMapManager().drawLine(rightLatLng, latLng1);
        List<LatLng> segmentLatLonOne = new ArrayList<>();
        segmentLatLonOne.add(new LatLng(28.18908812484137, 113.03201719433652));
        segmentLatLonOne.add(new LatLng(28.184759445068728, 113.03201719433652));
        //线段二
        List<LatLng> segmentLatLonTwo = new ArrayList<>();
        segmentLatLonTwo.add(new LatLng(28.189361039603316, 111.04214790560411));
        segmentLatLonTwo.add(new LatLng(28.189361039603316, 114.04214790560411));
        MapCreateManager.getMapManager().drawLineYellow(segmentLatLonOne);
        MapCreateManager.getMapManager().drawLineYellow(segmentLatLonTwo);
        MapCreateManager.getMapManager().setOnMarkerDragListener(new AMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                LogUtil.e("Marker", "开始拖动" + "");
                //航点拖拽
                //带加号的航点拖拽
                ObliquePhotographyUtil.getInstance().onMarkerDragStart(marker);
            }

            @Override
            public void onMarkerDrag(Marker marker) {
                //航点拖拽
                //带加号的航点拖拽
                ObliquePhotographyUtil.getInstance().onMarkerDrag(marker);
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                LogUtil.e("Marker", "结束拖动" + "");
                ObliquePhotographyUtil.getInstance().onMarkerDragEnd(marker);
            }
        });

        MapCreateManager.getMapManager().setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getObject() != null) {
                    try {
                        //marker点的类型 常量类 MapMarkerTypeConstant
                        ObliquePhotographyUtil.getInstance().onMarkerClick(marker);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                return false;
            }
        });

        MapCreateManager.getMapManager().setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                LogUtil.e("Marker", "======onMapClick=====" + "" + latLng.latitude + "================" + latLng.longitude);
                // 113.02743681652198=====28.166934427802392
                // 113.02743681652198=====28.166934427802392
                if (isFirstLoc) {
                    isFirstLoc = false;
                    ObliquePhotographyUtil.getInstance().onAddDraw(PolygonLineActivity.this, latLng);
                }
            }
        });

        double alat = 28.165795287154182;
        double alng = 113.02199423236485;

        double centerLat = 28.165795287154182;
        double centerLng = 113.02592210354092;
        List<LatLng> latLngs = new ArrayList<>();
        latLngs.add(new LatLng(alat, alng));
        latLngs.add(new LatLng(centerLat, centerLng));
        MapCreateManager.getMapManager().drawLine(latLngs);
        MapCreateManager.getMapManager().addMarker(new LatLng(centerLat, centerLng));
        //旋转测试
        LatLng tr = RouteUtil.transform(
                alng,
                alat,
                centerLng,
                centerLat,
                45, 1, 1);
        List<LatLng> latLngs2 = new ArrayList<>();
        latLngs2.add(tr);
        latLngs2.add(new LatLng(centerLat, centerLng));
        MapCreateManager.getMapManager().drawLine(latLngs2);
        // 1.1倍数
        //113.02599423236485=====28.165795287154182
        //113.02592210354092=====28.165744960807505
        //113.02584997471699=====28.165694634460824
        double distance = MapCalculationLogLatDistance.GetDistanceTwo(113.02599423236485, 28.165795287154182,
                113.02592210354092, 28.165744960807505);
        double distance2 = MapCalculationLogLatDistance.GetDistanceTwo(113.02599423236485, 28.165795287154182,
                113.02584997471699, 28.165694634460824);
        //倍数和距离的关系
        //1.1倍数 ===>9.027276987824582米 x = 100/9*0.1
        //1.2倍数 ===>18.054556586471936米
        //2.1倍数 ===>100

        LogUtil.d("数据", "距离" + distance);
        LogUtil.d("数据", "距离" + distance2);


    }


    private void initView() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_button1) {
                    ObliquePhotographyUtil.getInstance().setDipType(DipType.TYPE_CENTER);
                }
                if (checkedId == R.id.radio_button2) {
                    ObliquePhotographyUtil.getInstance().setDipType(DipType.TYPE_LEFT);
                }
                if (checkedId == R.id.radio_button3) {
                    ObliquePhotographyUtil.getInstance().setDipType(DipType.TYPE_TOP);
                }
                if (checkedId == R.id.radio_button4) {
                    ObliquePhotographyUtil.getInstance().setDipType(DipType.TYPE_RIGHT);
                }
                if (checkedId == R.id.radio_button5) {
                    ObliquePhotographyUtil.getInstance().setDipType(DipType.TYPE_BOTTOM);
                }

            }
        });
        tiltAngleValueSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    int mprogress = progress - 90;
                    if (mprogress >= -85 && mprogress <= -45) {
                        LogUtil.e("数据", "=======角度========>" + mprogress);
                        tiltAngleValue.setText("倾斜角度" + mprogress);
                        ObliquePhotographyUtil.getInstance().setTiltAngle(90 + mprogress);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        flyHeightValueSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    if (progress >= 25) {
                        flyHeightValue.setText("飞行高度" + progress);
                        ObliquePhotographyUtil.getInstance().setFlyHeight(progress);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        diskOverlapRatio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    diskOverlapRatioValue.setText("旁向重叠率" + progress);
                    ObliquePhotographyUtil.getInstance().setDiskOverlapRatio(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //边距
        seekbarDdg.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    edgValue.setText("边距 " + progress);
                    ObliquePhotographyUtil.getInstance().setEdgeDistance(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seekbarHead.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    rotationValue.setText("旋转 " + progress);
                    ObliquePhotographyUtil.getInstance().setmHeadDirection(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        initMapView();

        //反转航点
        findViewById(R.id.bt_reverse_map).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        findViewById(R.id.bt_clear_map).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ObliquePhotographyUtil.getInstance().clearMap();
                isFirstLoc = true;
            }
        });
        //删除航点
        findViewById(R.id.bt_revoke_map).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ObliquePhotographyUtil.getInstance().revokeWayPointEdgLine(new ObliquePhotographyUtil.MarkerCallback() {
                    @Override
                    public void onCallBack(int size) {

                    }
                });
            }
        });
    }


    private void initMapView() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap(LatLng latLng) {
        if (mTagmarker == null) {
            MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                    .position(latLng)
                    .draggable(true);
            mTagmarker = MapCreateManager.getMapManager().getaMap().addMarker(markerOption);
        } else {
            mTagmarker.setPosition(latLng);
        }
    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            mMapView.onDestroy();

        }
        ObliquePhotographyUtil.getInstance().onDestroy();
    }


    /**
     * 转高德地图经纬度
     *
     * @param sourceLatLng
     * @return
     */
    public LatLng latLngToGdLatLng(LatLng sourceLatLng) {
        CoordinateConverter converter = new CoordinateConverter(App.getContext());
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标点 LatLng类型
        converter.coord(sourceLatLng);
        // 执行转换操作
        LatLng desLatLng = converter.convert();
        return desLatLng;
    }


}
